//这是一个main包
package main

import (
	"fmt"
	"io"
	"bytes"
	"os"
	"time"

	nested "github.com/antonfisher/nested-logrus-formatter"
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/load"
	"github.com/shirou/gopsutil/v3/mem"
	log "github.com/sirupsen/logrus"
)

func getCPULoader() []float64 {
	percent, _ := cpu.Percent(time.Second, true)
	return percent
}
func getCPULoadavg() (float64, float64, float64) {
	avgStat, _ := load.Avg()
	return avgStat.Load1, avgStat.Load5, avgStat.Load15
}

//获取内存使用
func getMemoryUsed() float64 {
	state, _ := mem.VirtualMemory()
	return state.UsedPercent
}

func main() {
	log.SetLevel(log.TraceLevel)
	log.SetFormatter(&nested.Formatter{
		HideKeys:        true,
		TimestampFormat: "2006-01-02 15:04:05.000",
	})
	write1 := os.Stdout
	var logname bytes.Buffer
	logname.WriteString(time.Now().Format("log/20060102_150405"))
	logname.WriteString(".log")
	write2, err := os.OpenFile(logname.String(), os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		log.Fatalf("create log file error,%v", err)
	}
	log.SetOutput(io.MultiWriter(write1, write2))

	cnt, _ := cpu.Counts(true)
	log.Printf("cpu core num: %d", cnt)
	var ticker = time.NewTicker(time.Duration(time.Second * 1))
	go func(t *time.Ticker) {
		for {
			<-t.C
			load1, load5, load15 := getCPULoadavg()
			var buff bytes.Buffer
			for _,loader := range getCPULoader(){
				cpu := fmt.Sprintf("%.2f%% ",loader)
				buff.WriteString(cpu)
			}
			log.Printf("cpu loader:%s, mem used:%.2f%% load1:%.2f, load5:%.2f, load15:%.2f", buff.String(), getMemoryUsed(), load1, load5, load15)
		}
	}(ticker)

	for {
		fmt.Println("cputest is running...")
		time.Sleep(time.Duration(time.Second*10))
	}
}
